from flask import abort, jsonify
from flask import current_app
from flask import g
from flask import render_template
from flask import request

from info import constants, db
from info.models import News, Comment, CommentLike, User
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import news_blue


@news_blue.route('/comment_like', methods=["POST"])
@user_login_data
def set_comment_like():
    """评论点赞"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 获取参数
    comment_id = request.json.get("comment_id")
    action = request.json.get("action")

    # 判断参数
    if not all([comment_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if not action in ("add", "remove"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询评论数据
    try:
        comment = Comment.query.get(comment_id)
    except Exception as e:
        current_app.logger.errro(e)
        return jsonify(errno=RET.DBERR, errmsg="查询数据失败")

    if not comment:
        return jsonify(errno=RET.NODATA, errmsg="评论数据不存在")

    # 逻辑处理
    if action == "add":
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=user.id).first()
        if not comment_like:
            comment_like = CommentLike()
            comment_like.comment_id = comment_id
            comment_like.user_id = user.id
            db.session.add(comment_like)
            # 增加点赞条数
            comment.like_count += 1
    else:
        # 删除点赞数据
        comment_like = CommentLike.query.filter_by(comment_id=comment_id, user_id=user.id).first()
        if comment_like:
            db.session.delete(comment_like)
            # 减小点赞条数
            comment.like_count -= 1

    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.errro(e)
        db.session.rollback()
        return jsonify(errno=RET.DBERR, errmsg="操作失败")
    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blue.route('/followed_user', methods=["POST"])
@user_login_data
def followed_user():
    """关注/取消关注用户"""
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 被关注人数的用户id
    user_id = request.json.get("user_id")
    action = request.json.get("action")

    if not all([user_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if action not in ("follow", "unfollow"):
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 查询到关注用户的信息
    try:
        target_user = User.query.get(user_id)
    except Exception as e:
        current_app.logger.errro(e)
        return jsonify(errno=RET.DBERR, errmsg="未查询到数据库数据")

    if not target_user:
        return jsonify(errno=RET.NODATA, errmsg="未查到用户数据")

    # 逻辑处理
    if action == "follow":
        if target_user.followers.filter(User.id == user.id).count() > 0:
            return jsonify(errno=RET.DATAEXIST, errmsg="当前已关注")
        target_user.followers.append(user)
    else:
        if target_user.followers.filter(User.id == user.id).count() > 0:
            target_user.followers.remove(user)

    # 保存到数据
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.errro(e)
        return jsonify(errno=RET.DBERR, errmsg="数据保存错误")

    return jsonify(errno=RET.OK, errmsg="操作成功")


@news_blue.route('/news_comment', methods=["POST"])
@user_login_data
def news_comment():
    # 一 获取参数
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    news_id = request.json.get("news_id")
    comment_str = request.json.get("comment")
    parent_id = request.json.get("parent_id")

    # 二 校验参数
    if not all([news_id, comment_str]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    # 三 逻辑处理
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.errro(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="新闻无数据")

    # 创建评论模型
    comment = Comment()
    comment.user_id = user.id
    comment.news_id = news.id
    comment.content = comment_str
    if parent_id:
        comment.parent_id = parent_id

    # 提交数据库
    try:
        db.session.add(comment)
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.errro(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 四 返回数据
    return jsonify(errno=RET.OK, errmsg="成功", data=comment.to_dict())


# 收藏与取消收藏
@news_blue.route('/news_collect', methods=["POST"])
@user_login_data
def news_collect():
    # 所有需要判断用户登录的接口, 都应该县判断用户是否登录
    user = g.user
    if not user:
        return jsonify(errno=RET.SESSIONERR, errmsg="用户未登录")

    # 一获取参数
    news_id = request.json.get("news_id")
    action = request.json.get("action")

    # 二 校验参数
    if not all([news_id, action]):
        return jsonify(errno=RET.PARAMERR, errmsg="参数不全")

    if action not in ["collect", "cancel_collect"]:
        return jsonify(errno=RET.PARAMERR, errmsg="参数错误")

    # 三 逻辑处理
    # 3.1 查询新闻
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.errro(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    if not news:
        return jsonify(errno=RET.NODATA, errmsg="找不到该新闻")

    # 3.2 根据点击的状态值来判断如何操作
    if action == "collect":
        if news not in user.collection_news:
            user.collection_news.append(news)
    else:
        if news in user.collection_news:
            user.collection_news.remove(news)

    # 3.4 提交数据库
    try:
        db.session.commit()
    except Exception as e:
        current_app.logger.errro(e)
        return jsonify(errno=RET.DBERR, errmsg="保存失败")

    # 四.返回数据
    return jsonify(errno=RET.OK, errmsg="成功")


# 获取新闻详情
@news_blue.route('/<news_id>')
@user_login_data
def get_news_id(news_id):
    # 一.获取用户信息
    user = g.user

    # 二.点击排行数据 -- 查询后转字典返回
    news_models = None
    try:
        news_models = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS)
    except Exception as e:
        current_app.logger.errro(e)

    # 模型数据转字典数据
    click_news_list = []
    for news in news_models if news_models else []:
        click_news_list.append(news.to_basic_dict())

    # 三.查询新闻详情
    # 查询新闻数据 -- 没有就抛出404
    news = None
    try:
        news = News.query.get(news_id)
    except Exception as e:
        current_app.logger.errro(e)
        abort(404)

    if not news:
        abort(404)

    # 3.2 新闻的点击量加1
    news.clicks += 1

    # 3.3 提交数据库
    try:
        db.session.commit()
    except Exception as e:
        db.session.rollback()
        current_app.logger.errro(e)
        return jsonify(errno=RET.DBERR, errmsg="数据库错误")

    # 四.收藏 -- 用户登陆&收藏过该文章
    is_collected = False

    # 已登陆
    if user:
        # 判断新闻是否在用户的收藏新闻列表中
        if news in user.collection_news:
            is_collected = True

    # 五.新闻评论
    comment_models = []
    try:
        comment_models = Comment.query.filter(Comment.news_id == news_id).order_by(Comment.create_time.desc()).all()
    except Exception as e:
        current_app.logger.errro(e)

    comment_like_ids = []

    user =g.user
    if user:
        # 如果当前用户已经登录
        try:
            # 1. 获取所有评论的id
            comment_ids = [comment.id for comment in comment_models]

            # 2.如果有评论,就查询评论点赞表
            if len(comment_ids) > 0:
                # 取到当前用户在当前新闻的所有评论点赞记录
                comment_likes = CommentLike.query.filter(CommentLike.comment_id.in_(comment_ids),CommentLike.user_id == g.user.id).all()

                # 3.取出记录中所有的评论id
                comment_like_ids = [comment_like.comment_id for comment_like in comment_likes]
        except Exception as e:
            current_app.logger.errro(e)

    comment_list = []
    for item in comment_models if comment_models else []:

        comment_dict = item.to_dict()
        # 默认给所有的评论都增加一个is_like = False 的值
        comment_dict["is_like"] = False
        # 判断用户是否点赞该评论
        if user and item.id in comment_like_ids:
            comment_dict["is_like"] = True

        comment_list.append(comment_dict)

    # 六.关注 -- 用户登录&有作者信息
    is_followed = False
    # 用户登录&有作者信息
    if user and news.user:
        # 判断该作者的粉丝中有我关注
        if user in news.user.followers:
            is_followed = True

    data = {
        "user": user.to_index_dict() if user else None,
        "click_news_list": click_news_list,
        "news": news.to_dict(),
        "is_collected": is_collected,
        "comment_list": comment_list,
        "is_followed": is_followed
    }
    return render_template("news/detail.html", data=data)




























